<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            text-align: center;
        }
    </style>
</head>

<body>
    <h2>Revenue by Music Format, 1973–2018 --- 1973-2018年按音乐形式划分的收入</h2>
</body>
<script src="./d3@6.js"></script>
<script src="./color-legend.js"></script>
<script src="../jquery-1.11.1.min.js"></script>
<script>
    height = 500
    width = 1800
    margin = { top: 20, right: 30, bottom: 30, left: 30 }
    colors = new Map([
        ["LP/EP", "#2A5784"],
        ["Vinyl Single", "#43719F"],
        ["8 - Track", "#5B8DB8"],
        ["Cassette", "#7AAAD0"],
        ["Cassette Single", "#9BC7E4"],
        ["Other Tapes", "#BADDF1"],
        ["Kiosk", "#E1575A"],
        ["CD", "#EE7423"],
        ["CD Single", "#F59D3D"],
        ["SACD", "#FFC686"],
        ["DVD Audio", "#9D7760"],
        ["Music Video (Physical)", "#F1CF63"],
        ["Download Album", "#7C4D79"],
        ["Download Single", "#9B6A97"],
        ["Ringtones & Ringbacks", "#BE89AC"],
        ["Download Music Video", "#D5A5C4"],
        ["Other Digital", "#EFC9E6"],
        ["Synchronization", "#BBB1AC"],
        ["Paid Subscription", "#24693D"],
        ["On-Demand Streaming (Ad-Supported)", "#398949"],
        ["Other Ad-Supported Streaming", "#61AA57"],
        ["SoundExchange Distributions", "#7DC470"],
        ["Limited Tier Paid Subscription", "#B4E0A7"]
    ])


    var data = [];
    d3.csv('../music.csv', function (res) {
        data.push({ 'name': res['Format'], 'year': res['Year'], 'value': res['Revenue (Inflation Adjusted)'] })
    })


    setTimeout(function () {
        series = d3.stack()
            .keys(colors.keys())
            .value((group, key) => group.get(key).value)
            .order(d3.stackOrderReverse)
            (d3.rollup(data, ([d]) => d, d => d.year, d => d.name).values())
            .map(s => (s.forEach(d => d.data = d.data.get(s.key)), s))


        x = d3.scaleBand()
            .domain(data.map(d => d.year))
            .rangeRound([margin.left, width - margin.right])

        y = d3.scaleLinear()
            .domain([0, d3.max(series, d => d3.max(d, d => d[1]))]).nice()
            .range([height - margin.bottom, margin.top])

        color = d3.scaleOrdinal()
            .domain(colors.keys())
            .range(colors.values())


        xAxis = g => g
            .attr("transform", `translate(0,${height - margin.bottom})`)
            .call(d3.axisBottom(x)
                .tickValues(d3.ticks(...d3.extent(x.domain()), width / 80))
                .tickSizeOuter(0))


        yAxis = g => g
            .attr("transform", `translate(${margin.left},0)`)
            .call(d3.axisLeft(y)
                .tickFormat(x => (x / 1e9).toFixed(0)))
            .call(g => g.select(".domain").remove())
            .call(g => g.select(".tick:last-of-type text").clone()
                .attr("x", 3)
                .attr("text-anchor", "start")
                .attr("font-weight", "bold")
                .text(data.y))



        formatRevenue = x => (+(x / 1e9).toFixed(2) >= 1)
            ? `${(x / 1e9).toFixed(2)}B`
            : `${(x / 1e6).toFixed(0)}M`



        chart = chart => {
            const svg = d3.create("svg")
                .attr("viewBox", [0, 0, width, height]);

            svg.append("g")
                .selectAll("g")
                .data(series)
                .join("g")
                .attr("fill", ({ key }) => color(key))
                .call(g => g.selectAll("rect")
                    .data(d => d)
                    .join("rect")
                    .attr("x", d => x(d.data.year))
                    .attr("y", d => y(d[1]))
                    .attr("width", x.bandwidth() - 1)
                    .attr("height", d => y(d[0]) - y(d[1]))
                    .append("title")
                    .text(d => `${d.data.name}, ${d.data.year}${formatRevenue(d.data.value)}`));

            svg.append("g")
                .call(xAxis);

            svg.append("g")
                .call(yAxis);

            document.body.append(svg.node())
        }
        //初始化
        chart()
    }, 100)
</script>

</html>